<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >

  <div style="height: 50px;">
    <el-button @click="openDialog" :disabled="props.isDisabled">批量新增</el-button>
    <el-button @click="handleAdd" :disabled="props.isDisabled">添加明细</el-button>


    <InventoryForm ref="formRefAdd" @success="handleSuccess" />
    <InventoryForm2 ref="formRefAdd2" @success2="handleSuccess2" />

  </div>

    <el-table :data="formData" class="-mt-10px" style="height: 330px;" border>
      <el-table-column label="序号" type="index" width="100" />
 


      <el-table-column label="存货编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryCode" placeholder="请输入存货编码"  @click="openDialog2($index)"   :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="存货名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryName" placeholder="请选择存货名称"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventorySpecModel`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventorySpecModel" placeholder="请输入规格型号"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryUnitName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryUnitName" placeholder="请输入单位"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>



      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.qty`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.qty" placeholder="请输入数量" @input="calculateValues($index)" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税率" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.taxRate`"  class="mb-0px!">
            <el-input v-model="row.taxRate" placeholder="请输入税率" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.price`"  class="mb-0px!">
            <el-input v-model="row.price" placeholder="请输入单价" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="含税单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.taxPrice`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.taxPrice" placeholder="请输入含税单价" @input="calculateValues($index)" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.money`"  class="mb-0px!">
            <el-input v-model="row.money" placeholder="请输入金额" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="税额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.tax`"  class="mb-0px!">
            <el-input v-model="row.tax" placeholder="请输入税额" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="价税合计" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sum`"  class="mb-0px!">
            <el-input v-model="row.sum" placeholder="请输入价税合计" :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`"  class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link  :disabled="props.isDisabled">—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>

</template>
<script setup lang="ts">
import { SaleOrderApi } from '@/api/wms/saleorder'
import { InventoryVO, InventoryApi } from '@/api/wms/inventory';
import InventoryForm from '../../pomain/components/PomainInventoryForm.vue'
import InventoryForm2 from '../../pomain/components/PomainInventoryForm2.vue'

const props = defineProps<{
  pid: number | undefined  // 主表ID（主表的关联字段）
  isDisabled: boolean | undefined // 是否禁用表单           
}>()
const selectLoading = ref(false) // 表单的加载中
const inventoryList = ref([] as InventoryVO[]); // 存货列表
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      const initialData  = await SaleOrderApi.getSaleDetailListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.inventoryId) {
          const inventory = await InventoryApi.getInventory(item.inventoryId);
         
          return {
            ...item,
            inventoryName: inventory.name,
            inventoryCode: inventory.code,
            inventoryUnitName: inventory.unitName,
            inventorySpecModel: inventory.specModel,

          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 查询存货 */
const remoteInventory = (query: string) => {
  if (query) {
    selectLoading.value = true
    setTimeout(async () => {
      selectLoading.value = false
      inventoryList.value = await InventoryApi.getInventorySimpleList(query)
    }, 200)
  } else {
    setTimeout(async () => {
      const data = await InventoryApi.getInventoryPage({})
      inventoryList.value = data.list
    }, 100)
  }
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    pid: undefined,
    inventoryId: undefined,
    qty: undefined,
    taxRate: undefined,
    price: undefined,
    taxPrice: undefined,
    money: undefined,
    tax: undefined,
    sum: undefined,
    remark: undefined,
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 处理存货编码选择变化 */
const handleInventoryChange = (value, row) => {
  const selectedInventory = inventoryList.value.find(item => item.id === value);
  if (selectedInventory) {
    row.inventoryId = selectedInventory.id;
    row.inventoryName = selectedInventory.name;
    row.inventoryCode = selectedInventory.code;
    row.inventoryUnitName = selectedInventory.unitName;
    row.inventorySpecModel = selectedInventory.specModel; 
  }
};


//批量新增代码

const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  // 打开弹窗的逻辑
  formRefAdd.value.open(); // 假设子组件有一个 open 方法
};

const handleSuccess = (formData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', formData)
  // 可以在这里调用 API 获取数据等
  const inventoryCodes = formData.inventoryCode;
  console.log('Selected inventory codes:', inventoryCodes);
  // 调用确认选择的方法
  confirmSelection(inventoryCodes);
};


/** 确认选择的存货编码 */
const confirmSelection = async (inventoryCodes: any[]) => {
  try {
    formLoading.value = true;
    const selectedInventoriesData = await Promise.all(inventoryCodes.map(async (id) => {
      const inventory = await InventoryApi.getInventory(id);
      return {
        id: undefined,
        pid: props.pid,
        inventoryId: id,
        inventoryName: inventory.name,
        inventoryCode: inventory.code,
        inventoryUnitName: inventory.unitName,
        inventorySpecModel: inventory.specModel,
        qty: undefined,
        taxRate: inventory.taxRate,
        price: undefined,
        taxPrice: undefined,
        money: undefined,
        sum: undefined,
        cbmemo: undefined,
      };
    }));
    formData.value.push(...selectedInventoriesData);
  } finally {
    formLoading.value = false;
    selectedInventories.value = []; // 重置选中的存货编码
  }
};


const calculateValues = (index: number) => {
  const row = formData.value[index];
  console.log(row.taxPrice+'--'+row.qty+'--'+row.taxRate)
  if (row.taxPrice && row.qty ) {
    //含税单价
    const taxPrice = parseFloat(row.taxPrice.toString());
    //数量
    const qty = parseFloat(row.qty.toString());
    //税率
    const taxRate = parseFloat(row.taxRate.toString());

    // 计算单价
    const price = taxPrice / (1 + taxRate );
    row.price = price.toFixed(2);

    // 计算金额
    const money = price * qty;
    row.money = money.toFixed(2);

   // 计算价税合计
   const sum = taxPrice * qty;
    row.sum = sum.toFixed(2);

    // 计算税额
    const tax = sum - (price * qty);
    row.tax = tax.toFixed(2);
    

  }
};

// 点击弹出框内容

const formRefAdd2 = ref(null); // 确保变量名唯一
const selectedRowIndex = ref(-1); // 用于存储被点击行的索引

const openDialog2 = (index) => {
  selectedRowIndex.value = index;
  // 打开弹窗的逻辑
  formRefAdd2.value.open(event);
  // formRefAdd.value.open(); // 假设子组件有一个 open 方法
};

const handleSuccess2 = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);
  console.log('selectedRowIndex.value:', selectedRowIndex.value)

  if (selectedRowIndex.value !== -1) {
    console.log(formData.value[selectedRowIndex.value])
    formData.value[selectedRowIndex.value] = { ...getFormData.value, ...getFormData };
    formData.value[selectedRowIndex.value].taxRate =getFormData.irate
    
  }
};


defineExpose({ validate, getData })
</script>
